package com.kotlin.myapplication.network

import android.util.Log
import com.kotlin.myapplication.network.api.AllApi
import com.kotlin.myapplication.constant.SyncStateContract
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 *@lil
 *@创建时间 2019/10/30 10:04
 *@描述
 */

class RetrofitUtil {
    companion object {

        /**
         * 创建Retrofit
         */
        fun create(url: String): Retrofit {
            //显示日志级别
            val level: HttpLoggingInterceptor.Level = HttpLoggingInterceptor.Level.BODY
            //http请求日志用http做过滤标签 string.format() %转义异常
            var loggingInterceptor: HttpLoggingInterceptor = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { message ->
//                Log.v("HTTP-LOG : ", message)
            })
            loggingInterceptor.level = level
            //okHttpClientBuilder
            val okHttpClientBuilder = OkHttpClient.Builder()

            okHttpClientBuilder.connectTimeout(60, TimeUnit.SECONDS)
            okHttpClientBuilder.readTimeout(10, TimeUnit.SECONDS)
            //OkHttp进行添加拦截器loggingInterceptor
            okHttpClientBuilder.addInterceptor(loggingInterceptor)

            return Retrofit.Builder()
                    .baseUrl(url)
                    .client(okHttpClientBuilder.build())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build()
        }

        /**
         * 获取ServiceApi
         */
        fun <T> getService(url: String, service: Class<T>): T {
            return create(url).create(service)
        }

        /**
         * 添加业务url
         */
        val retrofitService: AllApi = getService(SyncStateContract.Constants.REQUEST_BASE_URL, AllApi::class.java)
        /**
         * 聚合天气
         */
        val weatherService: AllApi = getService(SyncStateContract.Constants.JUHE_WEATHER_URL, AllApi::class.java)

        /**
         * 聚合新闻
         */
        val newService: AllApi = getService(SyncStateContract.Constants.JUHE_NEWS_URL, AllApi::class.java)

        /**
         * 获取用户信息
         */
        val userService: AllApi = getService(SyncStateContract.Constants.USER_MODEL_URL, AllApi::class.java)

        /**
         * 注册用户
         */
        val registerService: AllApi = getService(SyncStateContract.Constants.USER_MODEL_URL, AllApi::class.java)
    }


}